package eu.vranckaert.workRegistrationWidget.activities;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.*;
import com.google.inject.Inject;
import eu.vranckaert.workRegistrationWidget.R;
import eu.vranckaert.workRegistrationWidget.domain.TimeRegistration;
import eu.vranckaert.workRegistrationWidget.service.RegistrationService;
import eu.vranckaert.workRegistrationWidget.service.WidgetLayoutBuilderService;
import eu.vranckaert.workRegistrationWidget.util.WidgetUpdater;
import roboguice.activity.GuiceActivity;

import java.util.Calendar;
import java.util.GregorianCalendar;

/**
 * @author Dirk Vranckaert
 *         Date: 4-jun-2010
 *         Time: 16:34:13
 */
public class EditRegistrationActivity extends GuiceActivity {
    private static final String LOG_TAG = EditRegistrationActivity.class.getName();

    private static final int DIALOG_ENDDATE_BEFORE_STARTDATE = 1;

    @Inject
    RegistrationService registrationService;

    @Inject
    WidgetLayoutBuilderService widgetLayoutBuilderService;

    private TimeRegistration registration;

    private int step = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle data = this.getIntent().getExtras();
        registration = (TimeRegistration) data.getSerializable("registration");
        Log.d(LOG_TAG, "Editing registration with id " + registration.getId());

        updateViewForStep();
    }

    private void updateViewForStep() {
        switch(step) {
            case 0:
                setContentView(R.layout.registration_edit_step1);

                final Calendar startCalendar = new GregorianCalendar();
                startCalendar.setTime(registration.getStartDate());

                final DatePicker startDatePicker = (DatePicker) findViewById(R.id.regEditStartDatePicker);
                startDatePicker.updateDate(startCalendar.get(Calendar.YEAR), startCalendar.get(Calendar.MONTH), startCalendar.get(Calendar.DAY_OF_MONTH));

                final TimePicker startTimePicker = (TimePicker) findViewById(R.id.regEditStartTimePicker);
                startTimePicker.setCurrentHour(startCalendar.get(Calendar.HOUR_OF_DAY));
                startTimePicker.setCurrentMinute(startCalendar.get(Calendar.MINUTE));
                startTimePicker.setIs24HourView(true);

                Button nextButtonStep1 = (Button) findViewById(R.id.regEditNext);
                Button cancelButtonStep1 = (Button) findViewById(R.id.regEditCancel);

                nextButtonStep1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.d(LOG_TAG, "Next button clicked from step " + step);

                        int year = startDatePicker.getYear();
                        int month = startDatePicker.getMonth();
                        int day = startDatePicker.getDayOfMonth();
                        int hour = startTimePicker.getCurrentHour();
                        int minute = startTimePicker.getCurrentMinute();

                        startCalendar.set(Calendar.YEAR, year);
                        startCalendar.set(Calendar.MONTH, month);
                        startCalendar.set(Calendar.DAY_OF_MONTH, day);
                        startCalendar.set(Calendar.HOUR_OF_DAY, hour);
                        startCalendar.set(Calendar.MINUTE, minute);

                        registration.setStartDate(startCalendar.getTime());

                        goToNextStep();
                    }
                });

                cancelButtonStep1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish(false);
                    }
                });

                break;
            case 1:
                setContentView(R.layout.registration_edit_step2);

                final Calendar stopCalendar = new GregorianCalendar();

                final DatePicker stopDatePicker = (DatePicker) findViewById(R.id.regEditStopDatePicker);
                final TimePicker stopTimePicker = (TimePicker) findViewById(R.id.regEditStopTimePicker);
                final CheckBox regNotYetEnded = (CheckBox) findViewById(R.id.regEditStopNotYetEnded);
                stopTimePicker.setIs24HourView(true);

                TimeRegistration latestRegistration = registrationService.getLatestTimeRegistration(this);
                Log.d(LOG_TAG, "Latest registration has id " + latestRegistration.getId());
                if(latestRegistration.getId() != registration.getId()) {
                    regNotYetEnded.setEnabled(false);
                }

                if (registration.getEndDate() != null && registration.getEndDate().getTime() > 0L) {
                    stopCalendar.setTime(registration.getEndDate());

                    stopDatePicker.updateDate(stopCalendar.get(Calendar.YEAR), stopCalendar.get(Calendar.MONTH), stopCalendar.get(Calendar.DAY_OF_MONTH));

                    stopTimePicker.setCurrentHour(stopCalendar.get(Calendar.HOUR_OF_DAY));
                    stopTimePicker.setCurrentMinute(stopCalendar.get(Calendar.MINUTE));
                    regNotYetEnded.setChecked(false);
                } else {
                    regNotYetEnded.setChecked(true);
                    stopDatePicker.setEnabled(false);
                    stopTimePicker.setEnabled(false);
                }

                regNotYetEnded.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                        if(checked) {
                            stopDatePicker.setEnabled(false);
                            stopTimePicker.setEnabled(false);
                        } else {
                            stopDatePicker.setEnabled(true);
                            stopTimePicker.setEnabled(true);
                        }
                    }
                });

                Button nextButtonStep2 = (Button) findViewById(R.id.regEditNext);
                Button cancelButtonStep2 = (Button) findViewById(R.id.regEditCancel);

                nextButtonStep2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.d(LOG_TAG, "Next button clicked from step " + step);
                        
                        if (regNotYetEnded.isChecked()) {
                            registration.setEndDate(null);
                        } else {
                            int year = stopDatePicker.getYear();
                            int month = stopDatePicker.getMonth();
                            int day = stopDatePicker.getDayOfMonth();
                            int hour = stopTimePicker.getCurrentHour();
                            int minute = stopTimePicker.getCurrentMinute();

                            stopCalendar.set(Calendar.YEAR, year);
                            stopCalendar.set(Calendar.MONTH, month);
                            stopCalendar.set(Calendar.DAY_OF_MONTH, day);
                            stopCalendar.set(Calendar.HOUR_OF_DAY, hour);
                            stopCalendar.set(Calendar.MINUTE, minute);

                            registration.setEndDate(stopCalendar.getTime());
                        }

                        if (registration.getEndDate() != null && registration.getStartDate().compareTo(registration.getEndDate()) > 0) {
                            showDialog(DIALOG_ENDDATE_BEFORE_STARTDATE);
                        } else {
                            goToNextStep();
                        }
                    }
                });

                cancelButtonStep2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish(false);
                    }
                });

                break;
            case 2:
                setContentView(R.layout.registration_edit_step3);

                Button finishButton = (Button) findViewById(R.id.regEditFinish);
                Button cancelButtonStep3 = (Button) findViewById(R.id.regEditCancel);

                finishButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish(true);
                    }
                });

                cancelButtonStep3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        finish(false);
                    }
                });
        }
    }

    private void goToNextStep() {
        step++;
        updateViewForStep();
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;

        switch (id) {
            case DIALOG_ENDDATE_BEFORE_STARTDATE:
                AlertDialog.Builder alertBuilder2 = new AlertDialog.Builder(this);
                alertBuilder2.setTitle(R.string.warning)
                           .setMessage(R.string.regEdit_exc_enddate_before_startdate)
                           .setCancelable(false)
                           .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.cancel();
                                }
                            });
                AlertDialog alertDialog2 = alertBuilder2.create();
                dialog = alertDialog2;
                break;
        }

        return dialog;
    }

    private void finish(boolean completed) {
        if (completed) {
            registrationService.saveOrUpdateRegistration(this, registration);
            updateWidget();
            setResult(RESULT_OK);
        } else {
            setResult(RESULT_CANCELED);
        }
        super.finish();
    }

    private void updateWidget() {
        TimeRegistration registration = registrationService.getLatestTimeRegistration(this);
        WidgetUpdater.updateWidget(this, registration, widgetLayoutBuilderService);
    }
}
